package sns.dao;

import java.util.List;

import org.hibernate.Query;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import sns.bean.Mblog;
import sns.bean.User;

public class MblogDao extends HibernateDaoSupport {

	public void save(Mblog mblog){
		getSession().save(mblog);
	}
	
	public void merge(Mblog mblog){
		getSession().merge(mblog);
	}
	
	public void delete(Mblog mblog){
		getSession().delete(mblog);
	}
	
	/**
	 * get mblog by its id
	 * 
	 * @param idmblog
	 * @return
	 */
	public Mblog getMblogById(Long idmblog){
		if(idmblog==null){
			return null;
		}
		Query q = getSession().createQuery("select mblog from Mblog as mblog where mblog.idmblog = :idmblog");
		q.setLong("idmblog", idmblog);
		return (Mblog)q.uniqueResult();
	}
	
	/**
	 * get the recent n mblogs of all users
	 * 
	 * @param n
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Mblog> getAllMblogs(int n){
		if(n<0){
			return null;
		}
		Query q = getSession().createQuery("select mblog from Mblog as mblog order by mblog.mblogTime desc");
		q.setFirstResult(0);
		q.setMaxResults(n);
		return (List<Mblog>)q.list();
	}
	
	/**
	 * get the users’ mblogs
	 * 
	 * @param users
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Mblog> getListUsersMblogs(List<User> users){
		if(users==null||users.size()==0){
			return null;
		}
		Query q = getSession().createQuery("select mblog from Mblog as mblog where mblog.publisher in (:users) order by mblog.mblogTime desc");
		q.setParameterList("users", users.toArray());
		return (List<Mblog>)q.list();
	}
	
	/**
	 * get mblogs of the user
	 * 
	 * @param user
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Mblog> getUserMblogs(User user){
		if(user==null){
			return null;
		}
		Query q = getSession().createQuery("select mblog from Mblog as mblog where mblog.publisher.iduser=:iduser order by mblog.mblogTime desc");
		q.setLong("iduser", user.getIduser());
		return (List<Mblog>)q.list();
	}
	
	/**
	 * get the number of mblogs of this user
	 * 
	 * @param user
	 * @return
	 */
	public int getMblogNum(User user){
		if(user==null){
			return 0;
		}
		Query q = getSession().createQuery("select count(*) from Mblog as mblog where mblog.publisher.iduser = :iduser");
		q.setLong("iduser", user.getIduser());
		return ((Long)q.uniqueResult()).intValue();
	}
}
